define(["../common"], function() {
	
	var $selCat = $("#selCat");
	var $rootWrapper = $("#wrapper_category_rootList");
	var $subWrapper = $("#wrapper_category_subList");
	var $container = $(".category-list");
	var $rootList = $rootWrapper.children();
	var $subList = $subWrapper.children();// .panel
	var $active;
	var subAdTmp = $("<div>").append($subList.find(".panel-body")).html();// .panel-body
	var rootIscroll, subIscroll;
	var preventDefault = function(e) {
		e.preventDefault(); 
	}
	
	$rootWrapper.get(0).addEventListener('touchmove', preventDefault, false);
	$subWrapper.get(0).addEventListener('touchmove', preventDefault, false);
	
	// 先缓存下模板
	$rootList.parseHtml().empty();
	$subList.parseHtml().empty();
	
	$.fn.extend({
		reHeight: function() {// 重新定义高度
			var $this = this;
			var height = $this.children().outerHeight();
			var maxHeight = $(window).scrollTop() + $(window).height() - $this.offset().top;
			if (height > maxHeight) {
				height = maxHeight;
			}
			$this.css("height", height + "px");
		}
	});
	
	$(window).on('scroll', reHeightIscroll)
	
	loadRoot();
	
	
	function loadRoot() {
		$rootList.empty();
				
		var loadPath = g_behaviorDomain + "/category/list/json";
		var vars = {type: 0};			
		var cachekey = $.param({path: loadPath, vars: vars});
		
		// 从缓存获取
		var cacheData = Common.getSessionStorage(cachekey);
		if (cacheData) {
			parseRoot($.parseJSON(cacheData));
			return;
		}
		
		// 从服务器获取
		$container.showLoading();
		$.ajax({
			url: loadPath + "?r=" + Math.random(),
			data: vars,
			dataType: 'text',
			success: function(data, textStatus, jqXHR) {
				Common.setSessionStorage(cachekey, data);
				parseRoot($.parseJSON(data));
			}
		});
	}
	
	function parseRoot(data) {
		$container.hideLoading();
		if (data.status !== 0) {
			$rootList.failMsg(data.message);
			return;
		}
		var list = data.result;
		if (!list || list.length == 0) {
			return;
		}
		/*
		list.unshift({
			catId: 0,
			name: "热门分类"
		});
		*/
		$rootList.parseHtml({
			data: list,
			afterNode: {
				root: registeEvent
			}
		});
		require(["iscroll"], function() {
			rootIscroll = new IScroll($rootWrapper.selector, { probeType: 3, mouseWheel: true,preventDefault: false });
			rootIscroll.on('scroll', toggleSelected);
			rootIscroll.on('scrollEnd', toggleSelected);
			
			reHeightIscroll();
			
			// 随机选中一个类目
			var $items = $rootWrapper.find("a");
			$active = $items.eq(parseInt(Math.random() * $items.length));
			$active.click();
			toggleSelected(rootIscroll);
		});
		
	}
	
	function loadSub(parentCat) {
		$subWrapper.opacity();
		$subList.empty();		
				
		// 广告
		parentCat.ad = {
			pic: "http://atta.51mxz.com/tmp/" + parseInt(Math.random() * 20) + ".jpg",// "def",
			url: "#"
		}
		var adHtml = subAdTmp.parseData(parentCat);
		$subList.append(adHtml);
		
		var loadPath = g_behaviorDomain + "/category/list/json";
		var vars = {parentId: parentCat.catId};			
		var cachekey = $.param({path: loadPath, vars: vars});
		
		// 从缓存获取
		var cacheData = Common.getSessionStorage(cachekey);
		if (cacheData) {
			parseSub($.parseJSON(cacheData), parentCat);
			return;
		}
		
		// 从服务器获取
		
		$subWrapper.showLoading();
		$.ajax({
			url: loadPath + "?r=" + Math.random(),
			data: vars,
			dataType: 'text',
			success: function(data, textStatus, jqXHR) {
				Common.setSessionStorage(cachekey, data);
				parseSub($.parseJSON(data), parentCat);
			}
		});
	}
	
	function parseSub(data, parentCat) {
		$subWrapper.hideLoading();
		if (data.status !== 0) {
			$subList.failMsg(data.message);
			return;
		}
		var list = data.result;
		
		// 没有子一级的,将上级作为子级显示
		if (!list || list.length == 0) {
			list = [];
			list.push(parentCat);
		}
		
		// 子一级不一定都有子二级,所以重新组织数据以便保证显示的体验效果
		// 构建一个子一级,并将所有没有子二级的子一级作为该构建子一级的子二级
		var customCat = {
			name: "",
			categories: []
		};
		var customList = [];
		
		for (var i in list) {
			var cat = list[i];
			if (!cat.categories || cat.categories.length == 0) {
				customCat.categories.push(cat);
			} else {
				customList.push(cat);
			}
		}
		customList.unshift(customCat);
		
		$subList.parseHtml({
			data: customList,
			afterNode: {
				//categories: registeEvent
			}
		});
		
		require(["iscroll"], function() {
			subIscroll = new IScroll($subWrapper.selector, { mouseWheel: true,preventDefault: false });
		});
		reHeightIscroll();
		$(window).scroll();
		
	}
	
	function registeEvent(category) {
		var cat = category;// category
		
		// 点击类目
		$("#cat_" + cat.catId).click(function() {
			// 根类
			if (cat.deep == 1) {
				// 选中相关
				$active.removeClass("active");
				$active = $(this);
				$active.addClass("active");
				$selCat.hide();
				$selCat.children().html($(this).html());
				// 加载子类
				loadSub(cat);				
				
			} // 子类
			else {
				
			}
		});
		
	}
	
	function reHeightIscroll() {
		$(".wrapper").reHeight();
		if (rootIscroll) {
			rootIscroll.refresh();
		}
		if (subIscroll) {
			subIscroll.refresh();
		}
	}
	
	function toggleSelected(iscroll) {
		var that = iscroll ? iscroll : this;
		if ($active.position().top <= Math.abs(that.y)) {
			$selCat.removeClass("bottom").show();
		} else if ($rootWrapper.outerHeight() + Math.abs(that.y) <= $active.position().top + $active.outerHeight()) {
			$selCat.addClass("bottom").show();
		} else {
			$selCat.hide();
		}		
	}
	
});